// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include "commoncppproblem21.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=21 lang=cpp
 *
 * [21] 合并两个有序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) 
    {
        ListNode* l1 = list1;
        ListNode* l2 = list2;
        ListNode* l3 = nullptr;
        ListNode* head = l3;
        if(l1 == nullptr)
            return l2;
        if(l2 == nullptr)
            return l1;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                if(l3 == nullptr)
                {
                    l3 = l1;
                    head = l3;
                }
                else
                {
                    l3->next = l1;
                    l3 = l3->next;
                }
                l1 = l1->next;
            }
            else 
            {
                if(l3 == nullptr)
                {
                    l3 = l2;
                    head = l3;
                }
                else
                {
                    l3->next = l2;
                    l3 = l3->next;
                }
                l2 = l2->next;
            }
        }
        if(l1)
            l3->next = l1;
        if(l2)
            l3->next = l2;
        return head;
    }
};
// @lc code=end

